﻿using Flurl;
using Flurl.Http;
using Flurl.Http.Configuration;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Starry.Wx.Core
{
    public class WxCoreService
    {
        protected IOptions<WxOptions> WxConfigs { get; init; }

        protected string AppId { get; init; }
        protected string AppSecret { get; init; }
        private const string _baseApiHost = "https://api.weixin.qq.com";

        public WxCoreService(IOptions<WxOptions> options)
        {
            this.WxConfigs = options;
            this.AppId = options.Value.AppId;
            this.AppSecret = options.Value.AppSecret;
        }

        protected static async Task<T> CallApiAsync<T>(string path,object body=null, HttpMethod method = null)
            where T : BaseResult
        {
            method ??= HttpMethod.Get;

            var url = $"{_baseApiHost}{path}";
            BaseResult result = null;
            if (method == HttpMethod.Get)
            {
                result = await url.GetJsonAsync<T>();
            }
            else if (method == HttpMethod.Post)
            {
                result = await url.PostJsonAsync(body).ReceiveJson<T>();
            }
            if (result != null && result.errcode != 0)
            {
                throw new CallApiException(result);
            }
            return result as T;
        }
    }
}
